package org.example.dyscript.dynamicscript;

import lombok.SneakyThrows;
import org.example.dyscript.compiler.JavaStringCompiler;

import java.util.Map;

public class JavaClassRule implements Rule {

  Rule rule = null;

  String classText = "package org.example.dyscript.dynamicscript;\n"
      + "\n"
      + "import java.util.Map;\n"
      + "\n"
      + "public class JavaHHHRule implements Rule {\n"
      + "\n"
      + "  /**\n"
      + "   * 判断下年龄和新老客\n"
      + "   */\n"
      + "  public boolean execute(Map<String, Object> parameters) {\n"
      + "    Integer aliScore = (Integer) parameters.get(\"ali_score\");\n"
      + "    Integer wxScore = (Integer) parameters.get(\"wx_score\");\n"
      + "    String pd_living_province = (String) parameters.get(\"pd_living_province\");\n"
      + "    String pd_census_province = (String) parameters.get(\"pd_census_province\");\n"
      + "\n"
      + "    return aliScore > 100\n"
      + "        && wxScore < 450\n"
      + "        && !pd_living_province.contains(\"乌克兰\")\n"
      + "        && pd_census_province.contains(\"吉尔吉斯斯坦\");\n"
      + "  }\n"
      + "\n"
      + "  public boolean evaluate(Map<String, Object> parameters) {\n"
      + "    Integer age = (Integer) parameters.get(\"age\");\n"
      + "    String vip = (String) parameters.get(\"vip\");\n"
      + "    return age > 18 && vip.contains(\"vip\");\n"
      + "  }\n"
      + "}";

  @SneakyThrows
  public JavaClassRule() {
    JavaStringCompiler compiler = new JavaStringCompiler();
    Map<String, byte[]> results = compiler.compile("JavaHHHRule.java", classText);
    Class<?> clazz = compiler.loadClass("org.example.dyscript.dynamicscript.JavaHHHRule", results);
    rule = (Rule) clazz.newInstance();
  }

  @Override
  public boolean execute(Map<String, Object> parameters) {
    return rule.execute(parameters);
  }

  @Override
  public boolean evaluate(Map<String, Object> parameters) {
    return rule.evaluate(parameters);
  }
}
